<?php

namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\model\Group as GroupModel;
use think\Db;

class GroupOutgo extends Admin
{
    protected $hisiModel = 'Group';//模型名称[通用添加、修改专用]
    protected $hisiValidate = 'Group';
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    public function initialize()
    {
        parent::initialize();
        $factoryKV = db('factory')->where([['status', '=', 1], ['type', '=', 1]])->order("order desc, id desc")->column('name', 'id');
        $outTypeMap = [1 => '裁', 2 => '车', 3 => '尾', 4 => '专机',];
        $this->assign('factoryKV', $factoryKV);
        $this->assign('outTypeMap', $outTypeMap);
    }

    public function index()
    {
        $factoryKV = db('factory')->where([['pid', '=', 0], ['status', '=', 1], ['type', '=', 1]])->order("order desc, id desc")->column('name', 'id');
        $outTypeMap = [1 => '裁', 2 => '车', 3 => '尾', 4 => '专机',];
        if ($this->request->isAjax()) {
            $where = $data = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $keyword = $this->request->param('keyword/s');
            $factorId = $this->request->param('factory_id/d', 0);
            $where[] = ['g.status', 'eq', 1];
            $where[] = ['f.type', '=', 1];
            if ($keyword) {
                $where[] = ['g.name', 'like', "%{$keyword}%"];
            }
            if ($factorId) {
                $where[] = ['factory_id', '=', $factorId];
            }
            $order = 'g.order desc, g.id desc';
            $list = GroupModel::alias('g')
                ->field('g.*,f.name as factory_name')
                ->where($where)
                ->join('factory f', 'f.id=g.factory_id')
                ->page($page)
                ->limit($limit)
                ->order($order)
                ->select();
            $data['count'] = GroupModel::alias('g')->join('factory f', 'f.id=g.factory_id')->where($where)->count();
            $list = empty($list) ? [] : $list->toArray();
            if (count($list) > 0) {
                foreach ($list as $k => $v) {
                    $list[$k]['out_type_txt'] = '';
                    if (trim($v['out_type']) != '') {
                        $v['out_type'] = explode(',', $v['out_type']);
                        foreach ($v['out_type'] as $k22 => $v22) {
                            $list[$k]['out_type_txt'] .= arrayGet($outTypeMap, $v22, '') . ',';
                        }

                    }
                }
            }
            $data['data'] = $list;
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }

        $assign = [
            'factoryKV' => [0 => '请选择'] + $factoryKV,
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     * [通用方法]编辑页面展示和保存
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function edit()
    {
        if ($this->request->isPost()) {// 数据验证

            $postData = $this->request->post();
            if (!isset($postData['out_type'])) {
                return $this->error('请选择委外类型');
            }
            $postData['out_type'] = implode(',', $postData['out_type']);
            $all_unit_ok = $this->_all_unit_ok($postData);
            if ($all_unit_ok == false) {
                return $this->error('如大于0时限定所有倍率相同值');
            }

            if ($this->hisiValidate) {

                if (strpos($this->hisiValidate, '\\') === false) {

                    if (defined('IS_PLUGINS')) {
                        $this->hisiValidate = 'plugins\\' . $this->request->param('_p') . '\\validate\\' . $this->hisiValidate;
                    } else {
                        $this->hisiValidate = 'app\\' . $this->request->module() . '\\validate\\' . $this->hisiValidate;
                    }

                }

                if ($this->hisiEditScene) {
                    $this->hisiValidate = $this->hisiValidate . '.' . $this->hisiEditScene;
                }

                $result = $this->validate($postData, $this->hisiValidate);
                if ($result !== true) {
                    return $this->error($result);
                }

            }
        }

        $where = [];
        if ($this->hisiModel) {// 通过Model更新

            $model = $this->model();

            $pk = $model->getPk();
            $id = $this->request->param($pk);

            $where[] = [$pk, '=', $id];
            $where = $this->getRightWhere($where);

            if ($this->request->isPost()) {

                if ($model->save($postData, $where) === false) {
                    return $this->error($model->getError());
                }

                return $this->success('保存成功', '');
            }

            $formData = $model->where($where)->find();

        } else if ($this->hisiTable) {// 通过Db更新

            $db = Db::name($this->hisiTable);
            $pk = $db->getPk();
            $id = $this->request->param($pk);

            $where[] = [$pk, '=', $id];
            $where = $this->getRightWhere($where);

            if ($this->request->isPost()) {

                if (!$db->where($where)->update($postData)) {
                    return $this->error('保存失败');
                }

                return $this->success('保存成功', '');
            }

            $formData = $db->where($where)->find();

        } else {

            return $this->error('当前控制器缺少属性（hisiModel、hisiTable至少定义一个）');

        }

        if (!$formData) {
            return $this->error('数据不存在或没有权限');
        }

        $this->assign('formData', $formData);

        $template = $this->request->param('template', 'form');

        return $this->fetch($template);
    }

    /**
     * [通用方法]添加页面展示和保存
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function add()
    {
        if ($this->request->isPost()) {

            $postData = $this->request->post();
            if (!isset($postData['out_type'])) {
                return $this->error('请选择委外类型');
            }
            $postData['out_type'] = implode(',', $postData['out_type']);
            //限定所有倍率相同值，如大于0时
            $all_unit_ok = $this->_all_unit_ok($postData);
            if ($all_unit_ok == false) {
                return $this->error('如大于0时限定所有倍率相同值');
            }

            if ($this->hisiValidate) {// 数据验证

                if (strpos($this->hisiValidate, '\\') === false) {

                    if (defined('IS_PLUGINS')) {
                        $this->hisiValidate = 'plugins\\' . $this->request->param('_p') . '\\validate\\' . $this->hisiValidate;
                    } else {
                        $this->hisiValidate = 'app\\' . $this->request->module() . '\\validate\\' . $this->hisiValidate;
                    }

                }

                if ($this->hisiAddScene) {
                    $this->hisiValidate = $this->hisiValidate . '.' . $this->hisiAddScene;
                }

                $result = $this->validate($postData, $this->hisiValidate);
                if ($result !== true) {
                    return $this->error($result);
                }

            }

            if ($this->hisiModel) {// 通过Model添加

                $model = $this->model();

                if (!$model->save($postData)) {
                    return $this->error($model->getError());
                }

            } else if ($this->hisiTable) {// 通过Db添加

                if (!Db::name($this->hisiTable)->insert($postData)) {
                    return $this->error('保存失败');
                }

            } else {

                return $this->error('当前控制器缺少属性（hisiModel、hisiTable至少定义一个）');

            }

            return $this->success('保存成功', '');
        }
        $formData = [
            'out_type' => '',
        ];
        $this->assign('formData', $formData);
        $template = $this->request->param('template', 'form');

        return $this->fetch($template);
    }

    /**
     * 如大于0时,限定所有倍率相同值，
     * @param $postData
     * @date 2021/11/27
     * @return bool
     * @author zhuguosen 905502314@qq.com
     */
    public function _all_unit_ok($postData)
    {
        $flag = [];
        foreach ($postData as $k => $v) {
            if ($postData['unit_cutting'] > 0) {
                $flag[] = $postData['unit_cutting'];
            }
            if ($postData['unit_workshop'] > 0) {
                $flag[] = $postData['unit_workshop'];
            }
            if ($postData['unit_tail'] > 0) {
                $flag[] = $postData['unit_tail'];
            }
            if ($postData['unti_manual'] > 0) {
                $flag[] = $postData['unti_manual'];
            }
        }
        foreach ($flag as $k => $v) {
            if ($flag[0] != $v) {
                return false;
            }
        }
        return true;
    }

    /**
     * 修改字段
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/25
     */
    public function editUnit()
    {
        $param = [
            'id' => $this->request->param('id/d', 0),
            'field' => $this->request->param('field/s', 0),
            'value' => $this->request->param('value/s', 0),
        ];
        switch ($param['field']) {
            default:
                $temp = db('group')->where([
                    ['id', '=', $param['id']],
                ])->update([
                    $param['field'] => $param['value'],
                ]);
                if ($temp == 1) {
                    return $this->Json(1, '修改成功', $temp);
                }
                return $this->Json(10, '修改失败', $temp);
                break;
        }
    }
}